<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="学习,Scrapy," />








  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.0" />






<meta name="description" content="前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。">
<meta property="og:type" content="article">
<meta property="og:title" content="Scrapy学习（三） 爬取豆瓣图书信息">
<meta property="og:url" content="http://yoursite.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/index.html">
<meta property="og:site_name" content="四畳半神话大系">
<meta property="og:description" content="前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。">
<meta property="og:image" content="http://oi6538cys.bkt.clouddn.com/00douban.png">
<meta property="og:updated_time" content="2017-02-05T02:07:14.412Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Scrapy学习（三） 爬取豆瓣图书信息">
<meta name="twitter:description" content="前言

Scrapy学习（一） 安装
Scrapy学习（二） 入门


有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。">
<meta name="twitter:image" content="http://oi6538cys.bkt.clouddn.com/00douban.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/"/>





  <title> Scrapy学习（三） 爬取豆瓣图书信息 | 四畳半神话大系 </title>
  <meta name="baidu-site-verification" content="UqNuoDzFTg" />
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c3916ebb87080111f91966b1291316d7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">四畳半神话大系</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
        
        <div class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger"  style="margin-left: 70%;display: block;">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i>搜索 <br />
            
          </a>
        </div>
        
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article" test>
  <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Amoyiki">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="四畳半神话大系">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="四畳半神话大系" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Scrapy学习（三） 爬取豆瓣图书信息
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-02-04T15:07:08+08:00">
                2017-02-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <a href="/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><blockquote>
<ul>
<li><a href="http://www.amoyiki.com/2017/01/29/Scrapy%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89-%E5%AE%89%E8%A3%85/" target="_blank" rel="external">Scrapy学习（一） 安装</a></li>
<li><a href="http://www.amoyiki.com/2017/01/30/Scrapy%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89-%E5%85%A5%E9%97%A8/" target="_blank" rel="external">Scrapy学习（二） 入门</a></li>
</ul>
</blockquote>
<p>有了前两篇的基础，就可以开始互联网上爬取我们感兴趣的信息了。因为暂时还没有学到如何模拟登陆，所以我就先抓像豆瓣这样不需要登陆的网站上的内容。<br><a id="more"></a><br>我的开发环境是 Win7 + PyChram + Python3.5 + MongoDB<br>爬虫的目标是豆瓣的日本文学标签下的所有书籍基本信息</p>
<h3 id="创建项目"><a href="#创建项目" class="headerlink" title="创建项目"></a>创建项目</h3><blockquote>
<p>scrapy startproject douban</p>
</blockquote>
<p>接着移动到<code>douban</code>目录下</p>
<blockquote>
<p>scrapy genspider book book.douban.com</p>
</blockquote>
<p>在spider目录下生成相应的BookSpider模板</p>
<h3 id="编写Item"><a href="#编写Item" class="headerlink" title="编写Item"></a>编写Item</h3><p>在items.py中编写我们需要的数据模型<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookItem</span><span class="params">(scrapy.Item)</span>:</span></span><br><span class="line">    book_name = scrapy.Field()</span><br><span class="line">    book_star = scrapy.Field()</span><br><span class="line">    book_pl = scrapy.Field()</span><br><span class="line">    book_author = scrapy.Field()</span><br><span class="line">    book_publish = scrapy.Field()</span><br><span class="line">    book_date = scrapy.Field()</span><br><span class="line">    book_price = scrapy.Field()</span><br></pre></td></tr></table></figure></p>
<h3 id="编写Spider"><a href="#编写Spider" class="headerlink" title="编写Spider"></a>编写Spider</h3><p>访问豆瓣的<a href="https://book.douban.com/tag/%E6%97%A5%E6%9C%AC%E6%96%87%E5%AD%A6?start=0" target="_blank" rel="external">日本文学</a>标签,将url的值写到<code>start_urls</code>中。接着在Chrome的帮助下，可以看到每本图书是在<code>ul#subject-list &gt; li.subject-item</code><br><img src="http://oi6538cys.bkt.clouddn.com/00douban.png" alt="日本文学"><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookSpider</span><span class="params">(scrapy.Spider)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        sel = Selector(response)</span><br><span class="line">        book_list = sel.css(<span class="string">'#subject_list &gt; ul &gt; li'</span>)</span><br><span class="line">        <span class="keyword">for</span> book <span class="keyword">in</span> book_list:</span><br><span class="line">            item = BookItem()</span><br><span class="line">            item[<span class="string">'book_name'</span>] = book.xpath(<span class="string">'div[@class="info"]/h2/a/text()'</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_star'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='rating_nums']/text()"</span>).extract()[</span><br><span class="line">                <span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_pl'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='pl']/text()"</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            pub = book.xpath(<span class="string">'div[@class="info"]/div[@class="pub"]/text()'</span>).extract()[<span class="number">0</span>].strip().split(<span class="string">'/'</span>)</span><br><span class="line">            item[<span class="string">'book_price'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_date'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_publish'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_author'</span>] = <span class="string">'/'</span>.join(pub)</span><br><span class="line">            <span class="keyword">yield</span> item</span><br></pre></td></tr></table></figure></p>
<p>测试一下代码是否有问题</p>
<blockquote>
<p>scrapy crawl book -o items.json</p>
</blockquote>
<p>奇怪的发现，items.json内并没有数据，后头看控制台中的DEBUG信息</p>
<blockquote>
<p>2017-02-04 16:15:38 [scrapy.core.engine] INFO: Spider opened<br>2017-02-04 16:15:38 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)<br>2017-02-04 16:15:38 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023<br>2017-02-04 16:15:39 [scrapy.core.engine] DEBUG: Crawled (403) <get https:="" book.douban.com="" robots.txt=""> (referer: None)<br>2017-02-04 16:15:39 [scrapy.core.engine] DEBUG: Crawled (403) <get https:="" book.douban.com="" tag="" %e6%97%a5%e6%9c%ac%e6%96%87%e5%ad%a6?start="0"> (referer: None)</get></get></p>
</blockquote>
<p>爬取网页时状态码是403。这是因为服务器判断出爬虫程序，拒绝我们访问。<br>我们可以在settings中设定<code>USER_AGENT</code>的值，伪装成浏览器访问页面。</p>
<blockquote>
<p>USER_AGENT = “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”</p>
</blockquote>
<p>再试一次，就发现items.json有值了。但仔细只有第一页的数据，如果我们想要爬取所有的数据，就需要爬完当前页后自动获得下一页的url，以此类推爬完所有数据。<br>所以我们对spider进行改造。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">    sel = Selector(response)</span><br><span class="line">    book_list = sel.css(<span class="string">'#subject_list &gt; ul &gt; li'</span>)</span><br><span class="line">    <span class="keyword">for</span> book <span class="keyword">in</span> book_list:</span><br><span class="line">        item = BookItem()</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            item[<span class="string">'book_name'</span>] = book.xpath(<span class="string">'div[@class="info"]/h2/a/text()'</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_star'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='rating_nums']/text()"</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            item[<span class="string">'book_pl'</span>] = book.xpath(<span class="string">"div[@class='info']/div[2]/span[@class='pl']/text()"</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">            pub = book.xpath(<span class="string">'div[@class="info"]/div[@class="pub"]/text()'</span>).extract()[<span class="number">0</span>].strip().split(<span class="string">'/'</span>)</span><br><span class="line">            item[<span class="string">'book_price'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_date'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_publish'</span>] = pub.pop()</span><br><span class="line">            item[<span class="string">'book_author'</span>] = <span class="string">'/'</span>.join(pub)</span><br><span class="line">            <span class="keyword">yield</span> item</span><br><span class="line">        <span class="keyword">except</span>:</span><br><span class="line">            <span class="keyword">pass</span></span><br><span class="line">    nextPage = sel.xpath(<span class="string">'//div[@id="subject_list"]/div[@class="paginator"]/span[@class="next"]/a/@href'</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">    <span class="keyword">if</span> nextPage:</span><br><span class="line">        next_url = <span class="string">'https://book.douban.com'</span>+nextPage</span><br><span class="line">        <span class="keyword">yield</span> scrapy.http.Request(next_url,callback=self.parse)</span><br></pre></td></tr></table></figure></p>
<p>其中<code>scrapy.http.Request</code>会回调parse函数，用try…catch是因为豆瓣图书并不是格式一致的。遇到有问题的数据，就抛弃不用。</p>
<h3 id="突破反爬虫"><a href="#突破反爬虫" class="headerlink" title="突破反爬虫"></a>突破反爬虫</h3><p>一般来说，如果爬虫速度过快。会导致网站拒绝我们的访问，所以我们需要在settings设置爬虫的间隔时间，并关掉COOKIES</p>
<blockquote>
<p>DOWNLOAD_DELAY = 2<br>COOKIES_ENABLED = False</p>
</blockquote>
<p>或者，我们可以设置不同的浏览器UA或者IP地址来回避网站的屏蔽<br>下面用更改UA来作为例子。<br>在middlewares.py,编写一个随机替换UA的中间件，每个request都会经过middleware。<br>其中<code>process_request</code>，返回<code>None</code>，Scrapy将继续到其他的middleware进行处理。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RandomUserAgent</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,agents)</span>:</span></span><br><span class="line">        self.agents = agents</span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">from_crawler</span><span class="params">(cls,crawler)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> cls(crawler.settings.getlist(<span class="string">'USER_AGENTS'</span>))</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_request</span><span class="params">(self,request,spider)</span>:</span></span><br><span class="line">        request.headers.setdefault(<span class="string">'User-Agent'</span>,random.choice(self.agents))</span><br></pre></td></tr></table></figure></p>
<p>接着道<code>settings</code>中设置<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">DOWNLOADER_MIDDLEWARES = &#123;</span><br><span class="line">'douban.middlewares.RandomUserAgent': 1,</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line">USER_AGENTS = [</span><br><span class="line">    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",</span><br><span class="line">    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",</span><br><span class="line">    ...</span><br><span class="line">]</span><br></pre></td></tr></table></figure></p>
<p>再次运行程序，显然速度快了不少。</p>
<h3 id="保存到MongoDB"><a href="#保存到MongoDB" class="headerlink" title="保存到MongoDB"></a>保存到MongoDB</h3><p>接下来我们要将数据保存到数据库做持久化处理(这里用MongoDB举例，保存到其他数据库同理)。<br>这部分处理是写在<code>pipelines</code>中。在此之前我们还要先安装连接数据库的驱动。</p>
<blockquote>
<p>pip install pymongo</p>
</blockquote>
<p>我们在<code>settings</code>写下配置<br><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># MONGODB configure</span></span><br><span class="line"><span class="attr">MONGODB_SERVER</span> = <span class="string">'localhost'</span></span><br><span class="line"><span class="attr">MONGODB_PORT</span> = <span class="number">27017</span></span><br><span class="line"><span class="attr">MONGODB_DB</span> = <span class="string">'douban'</span></span><br><span class="line"><span class="attr">MONGODB_COLLECTION</span> = <span class="string">"book"</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MongoDBPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        connection = MongoClient(</span><br><span class="line">            host=settings[<span class="string">'MONGODB_SERVER'</span>],</span><br><span class="line">            port=settings[<span class="string">'MONGODB_PORT'</span>]</span><br><span class="line">        )</span><br><span class="line">        db = connection[settings[<span class="string">'MONGODB_DB'</span>]]</span><br><span class="line">        self.collection = db[settings[<span class="string">'MONGODB_COLLECTION'</span>]]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        self.collection.insert(dict(item))</span><br><span class="line">        log.msg(<span class="string">"Book  added to MongoDB database!"</span>,</span><br><span class="line">                level=log.DEBUG, spider=spider)</span><br><span class="line">        <span class="keyword">return</span> item</span><br></pre></td></tr></table></figure>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><p>将运行项目的时候控制台中输出的DEBUG信息保存到log文件中。只需要在<code>settings</code>中设置</p>
<blockquote>
<p>LOG_FILE = “logs/book.log”</p>
</blockquote>
<p>项目代码地址：<a href="https://github.com/amoyiki/LearnedAndProTest/tree/master/douban" target="_blank" rel="external">豆瓣图书爬虫</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/学习/" rel="tag"># 学习</a>
          
            <a href="/tags/Scrapy/" rel="tag"># Scrapy</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/30/Scrapy学习（二）-入门/" rel="next" title="Scrapy学习（二） 入门">
                <i class="fa fa-chevron-left"></i> Scrapy学习（二） 入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/02/13/Scrapy学习（四）-爬取微博数据/" rel="prev" title="Scrapy学习（四） 爬取微博数据">
                Scrapy学习（四） 爬取微博数据 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/"
           data-title="Scrapy学习（三） 爬取豆瓣图书信息" data-url="http://yoursite.com/2017/02/04/Scrapy学习（三）-爬取豆瓣图书信息/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Amoyiki" />
          <p class="site-author-name" itemprop="name">Amoyiki</p>
          <p class="site-description motion-element" itemprop="description">个人BLOG</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">36</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">8</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/amoyiki" target="_blank" title="Zhihu">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  Zhihu
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/amoyiki" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建项目"><span class="nav-number">2.</span> <span class="nav-text">创建项目</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写Item"><span class="nav-number">3.</span> <span class="nav-text">编写Item</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写Spider"><span class="nav-number">4.</span> <span class="nav-text">编写Spider</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#突破反爬虫"><span class="nav-number">5.</span> <span class="nav-text">突破反爬虫</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#保存到MongoDB"><span class="nav-number">6.</span> <span class="nav-text">保存到MongoDB</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其他"><span class="nav-number">7.</span> <span class="nav-text">其他</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Amoyiki</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

<div class="busuanzi-count">

  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span></span>
  

  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"amoyiki"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  








  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  


</body>
</html>
